import axios from 'axios';

import { setAccessToken, getAccessToken } from '../utils/auth';
const API_URL = 'http://localhost:8010/auth';

// 登录函数
export const login = async (username: string, password: string) => {
  const response = await axios.post(`${API_URL}/login`, 
    `username=${username}&password=${password}&grant_type=password`, 
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      withCredentials: true
    }
  );
  setAccessToken(response.data.access_token);
  return response.data;
};

// 获取受保护内容
export const fetchProtectedData = async () => {
  const token = getAccessToken();
  const response = await axios.get(`${API_URL}/protected`, {
    headers: {
      'Authorization': `Bearer ${token}`
    },
    withCredentials: true
  });
  return response.data;
};

// 刷新令牌
export const refreshToken = async () => {
  const response = await axios.post(`${API_URL}/refresh-token`, {}, {
    withCredentials: true
  });
  return response.data;
};

// 登出
export const logout = async () => {
  await axios.post(`${API_URL}/logout`, {}, {
    withCredentials: true
  });
};

// 获取存储状态
export const getStorageStatus = async () => {
  const response = await axios.get(`${API_URL}/storage-status`, {
    withCredentials: true
  });
  return response.data;
};

// 持久化内存存储
export const persistMemoryStore = async () => {
  const response = await axios.post(`${API_URL}/persist-memory-store`, {}, {
    withCredentials: true
  });
  return response.data;
};